package com.shopping.cart

import com.shopping.cart.Image
import com.shopping.cart.Item
import com.shopping.cart.ItemCategory
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import net.sf.ehcache.Element


class ImageController {

    def scaffold = true
    def cacheManager

    def index = {
        UploadCommand cmd = new UploadCommand()
        cmd.item = new Item()
        render(view: 'uploadForm', model: [cmd: cmd])
    }


    def upload = {UploadCommand cmd ->

        if (cmd.category.validate()) {
            cmd.item.addToCategories(cmd.category)
        }

        if (!cmd.validate() || !cmd.item.save()) {
            render(view: 'uploadForm', model: [cmd: cmd])
        }
        else {
            cmd.images.each {
                createImage(it, cmd)
            }

            flash.message = 'Item has been successfully added'
            cmd = new UploadCommand()
            cmd.item = new Item()
            cmd.category = new ItemCategory()
            render(view: 'uploadForm', model: [cmd: cmd])
        }
    }

    def uploadAndShowItems = {UploadCommand cmd ->
        if (cmd.category.validate()) {
            cmd.item.addToCategories(cmd.category)
        }

        if (!cmd.validate() || !cmd.item.save()) {
            render(view: 'uploadForm', model: [cmd: cmd])
        }
        else {
            cmd.images.each {
                createImage(it, cmd)
            }
            flash.message = 'Item has been successfully added'
            redirect(uri: '/item/list')
        }
    }

    def showImage = {
        def fileName = "${ConfigurationHolder.config.uploadFiles.directory}/${params.id}"

        boolean found = false
        File image = new File(fileName)
        if (image.exists() && image.canRead()) {
            byte[] b = image.readBytes();
            response.setContentLength(b.length)
            response.getOutputStream().write(b)
            found = true
        }

        if (!found) {
            response.sendError(404);
        }
    }

    private void createImage(def img, cmd) {
        Image image = new Image(name: img.name, location: "./uploadedFiles/${img.name}")
//        image.save(flush:true)
        //TODO remove as this is only to test ehcache working
//        println "addign to cache ${cacheManager}"
//        println "addign to cache ${cacheManager.getCache('exampleCache')}"
//        cacheManager.getCache('exampleCache')?.put(new Element(image, image))

        if (img && !img.empty) {
            String directory = "${ConfigurationHolder.config.uploadFiles.directory}/${cmd.item.id}"
            File file = new File(directory)
            if (file.mkdirs()) {
                img.transferTo(new File("${directory}/${img.originalFilename}"))

//                Image image = new Image(name: img.name, location: "./uploadedFiles/${img.name}")



                cmd.item.addToImages image
            }
        }
    }

}

class UploadCommand {
    List images = []
    Item item
    ItemCategory category

    static constraints = {
        images minSize: 1
        category nullable: false
    }
}